package cc.core.view.jusfan;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.widget.RelativeLayout;


/**
 * Created by 春凡 on 2014/11/20.
 */
public class SoftInputListener extends RelativeLayout {
    private OnSoftInputListener mListener;
    private int screenHeight, screenWidth;
    private float density;

    public SoftInputListener(Context context) {
        super(context);
        init(context);
    }

    public SoftInputListener(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    public SoftInputListener(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
       int height =  getResources().getDisplayMetrics().heightPixels;
        int width =  getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    private boolean callBack=false;
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        boolean isShowing;
        isShowing = screenHeight - b > (250 * density);

        if(mListener!=null && isShowing==!callBack) {
            mListener.softInput(isShowing);
            callBack=isShowing;
        }
    }

    public void setOnSoftInputListener(final Activity activity, OnSoftInputListener listener) {
        this.mListener = listener;
        post(new Runnable() {
            @Override
            public void run() {
                DisplayMetrics metrics = new DisplayMetrics();
                activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
                screenHeight = metrics.heightPixels;
                screenWidth = metrics.widthPixels;
                density=metrics.density;

            }
        });
    }

    public interface OnSoftInputListener {
        void softInput(boolean isShowing);
    }
}
